﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SyndicateBusiness.Classes;
using SyndicateDAO.DatabaseObject;
using System.DirectoryServices;

namespace SyndicateTest
{
    /// <summary>
    /// Summary description for UnitTest1
    /// </summary>
    [TestClass]
    public class UnitTest1
    {
        public UnitTest1()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        private TestContext testContextInstance;

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext
        {
            get
            {
                return testContextInstance;
            }
            set
            {
                testContextInstance = value;
            }
        }

        #region Additional test attributes
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test 
        // [TestInitialize()]
        // public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion

        [TestMethod]
        public void TestMethod1()
        {
           // ResultBL ResultBL = new ResultBL();

            //var content = ResultBL.DownloadResults("http://www.national-lottery.co.uk/player/lotto/results/downloadResultsCSV.ftl");


           // string text = "07-Jun-2011,25,38,40,6,36,10,4,\"MVY348186,MVZ001857\"";

         //   ResultObjectEuroMIllions re = new ResultObjectEuroMIllions(text);

         //   Console.Write(re.Raffle);
            LdapAuthentication a = new LdapAuthentication("LDAP://biggroup.lan");

            bool auth = a.IsAuthenticated("biggroup.lan", "piotr.krzesinski", "karolina123A");
            //c= LDAPAuth("piotr.krzesinski", "karolina123A");

            Assert.IsTrue(auth);
        }

        private bool LDAPAuth(string u, string p)
        {


            DirectoryEntry dir = new DirectoryEntry("LDAP://bigserver.biggroup.lan/DC=bigserver,DC=biggroup,DC=lan",u,p);// new DirectoryEntry("LDAP://bigserver.biggroup.lan", u, p, AuthenticationTypes.SecureSocketsLayer);
            try
            {
                using (DirectorySearcher search = new DirectorySearcher(dir))
                {
                    search.ServerTimeLimit = new TimeSpan(0, 0, 5);
                    search.ClientTimeout = new TimeSpan(0, 0, 5);
                    SearchResultCollection result = search.FindAll();
                }
            }

            catch
            {
                return false;
            }

            return true;
        }
        /*
        public static bool UserExists(string UserName)
        {
            DirectoryEntry de = GetDirectoryObject("/" + GetLDAPDomain());
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectCategory=user)(cn=" + UserName + "))";
            SearchResultCollection results = deSearch.FindAll();
            if (results.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        */
    }

    public class LdapAuthentication
    {
        private String _path;
        private String _filterAttribute;

        public LdapAuthentication(String path)
        {
            _path = path;
        }

        public bool IsAuthenticated(String domain, String username, String pwd)
        {
            String domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);

            try
            {	//Bind to the native AdsObject to force authentication.			
                Object obj = entry.NativeObject;

                DirectorySearcher search = new DirectorySearcher(entry);

                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();

                if (null == result)
                {
                    return false;
                }

                //Update the new path to the user in the directory.
                _path = result.Path;
                _filterAttribute = (String)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                throw new Exception("Error authenticating user. " + ex.Message);
            }

            return true;
        }

        public String GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(_path);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();

                int propertyCount = result.Properties["memberOf"].Count;

                String dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (String)result.Properties["memberOf"][propertyCounter];

                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }

                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");

                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }
    }

}
